<template>
    <div @click="playVoice" class="voiceWrapper my-1 btn btn-sm btn-outline-secondary">
      <span><font-awesome-icon :icon="['fas', 'play']" v-show="!playState" /></span>
      <span><font-awesome-icon :icon="['fas', 'pause']" v-show="playState" /></span>
      <span class="user-select-none">&ensp;&ensp;{{duration}}</span>
      <audio :id="'voice'+voiceId" :src="voiceSrc" preload="auto"></audio>
    </div>
</template>

<style scoped>
  .voiceWrapper {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
  }
</style>

<script setup>
import {defineProps, onMounted, ref, watch} from 'vue'
const duration = ref()
const playState = ref(false)
let audio

watch(playState, (newVal)=>{
  audio = document.getElementById(`voice${props.voiceId}`)
  if (newVal) {
    audio.play()
  } else {
    audio.pause()
  }
})

onMounted(async ()=>{
  audioTime(document.querySelector('#voice'+props.voiceId))
  setTimeout(()=>{
    duration.value = document.querySelector('#voice'+props.voiceId).duration.toFixed()+'″'
  },500)
})

const props = defineProps({
  voiceSrc: String,
  voiceId: Number
});

const playVoice = () => {
  playState.value = !playState.value
}

function audioTime(node) {
  node.onloadeddata = e => {
    const audioTarget = e.target
    if (audioTarget.duration === Infinity) {
      audioTarget.currentTime = 1e101
      audioTarget.ontimeupdate = () => {
        audioTarget.ontimeupdate = () => {return void 0;}
        audioTarget.currentTime = 1e101
        audioTarget.currentTime = 0
      }
    }
  }
}
</script>